/*
** nopCommerce one page checkout
*/

var Checkout = {
    shippingAddressSection: false,
    billingAddressSection: false,
    shippingMethodSection: false,
    paymentMethodSection: false,
    paymentInfoSection: false,
    confirmSection: false,
    checkoutWrapper: false,
    loadingBlock: false,
    editSectionUrl: false,
    failureUrl: false,

    init: function (shippingAddressSection, billingAddressSection, shippingMethodSection, paymentMethodSection, paymentInfoSection, confirmSection, checkoutWrapper, loadingBlock, editSectionUrl, failureUrl) {
        this.shippingAddressSection = shippingAddressSection;
        this.billingAddressSection = billingAddressSection;
        this.shippingMethodSection = shippingMethodSection;
        this.paymentMethodSection = paymentMethodSection;
        this.paymentInfoSection = paymentInfoSection;
        this.confirmSection = confirmSection;
        this.checkoutWrapper = checkoutWrapper;
        this.loadingBlock = loadingBlock;
        this.editSectionUrl = editSectionUrl;
        this.failureUrl = failureUrl;
    },

    ajaxFailure: function () {
        location.href = Checkout.failureUrl;
    },

    activateSection: function (section, content, samesection) {
        var _this = this;
        if (samesection) {
            section.css("opacity", 0).html(content);
        } else {
            section.html(content);
        }
        this.checkoutWrapper.stop().animate({ "height": section.height() }, 200, function () {
            section.stop().animate({ "opacity": 1 });
            _this.checkoutWrapper.css("height", "auto");
        });
    },

    addressOperation: function (elem, e) {
        $(".address-delete-confirm").remove();
        $("#opcaddresscontinue").hide();
        var scenario, addressType, data, addressId, loadingtext,
        url = elem.attr("data-url"),
        addressType = elem.attr("data-type"),
        element = elem,
        section = elem.closest(".section"),
        isEditing = false,
        _this = this;

        if (element.attr("data-id")) {
            addressId = parseInt(element.attr("data-id"));
        }
        if (section.find("#isEditing").length) {
            isEditing = true;
        }
        data = { addressType: addressType, addressId: addressId, isEditing: isEditing };

        if (element.hasClass("checkout-address-change-button")) {
            // Change currently selected address
            loadingtext = "Select an Address";
            scenario = 1;
        }
        if (element.hasClass("checkout-address-new-button")) {
            // Request new address form
            loadingtext = "Creating an Address";
            scenario = 2;
        }
        if (element.hasClass("checkout-address-clear-button")) {
            // Clear selected address
            loadingtext = "Clearing Address";
            scenario = 3;
        }
        if (element.hasClass("checkout-address-edit-button")) {
            // Edit existing addresses
            scenario = 4;
        }
        if (element.hasClass("checkout-address-delete-button")) {
            // Delete existing address
            scenario = 5;
        }
        if (element.hasClass("checkout-address-save-button")) {
            // Save address form
            data = element.closest('form').append('<input type="hidden" name="addressType" value="' + addressType + '" class="temp-form-input" />').serializeArray();
            $('.temp-form-input').remove();
            scenario = 6;
        }
        if (element.hasClass("checkout-address-select-button")) {
            // Select an address
            scenario = 7;
        }
        if (element.hasClass("checkout-address-cancel-button")) {
            // Cancels action and back to addresses display
            scenario = 8;
        }
        var loadingelement = $(".checkout-address-loading");
        // Pre-action animations
        if (scenario != 5) {
            if (scenario >= 1 && scenario <= 3) {
                $(".checkout-address-display").stop().animate({ "height": 0 });
                $(".checkout-loading").stop().animate({ "opacity": 0 }, function () {
                    $(this).hide();
                });

                loadingelement.css("opacity", 0).show().stop().animate({ "opacity": 1 });
            }
            $(".checkout-address-section").stop().animate({ "height": 0 });
            if (scenario == 2 || (scenario >= 4 && scenario <= 7)) {
                var height = $(".checkout-loading").outerHeight(true);
                $(".checkout-address-form-loading").css("opacity", 0).stop().animate({ "height": height, "opacity": 1 });
            }
            _this.addressOperationAction(_this, section, scenario, url, data, loadingelement);
        } else {
            $(".address-delete-confirm").remove();
            elem.closest(".address-render").append('<div class="address-delete-confirm"><div class="address-delete-confirm-wrapper"><p>Delete this address?</p><div><input type="button" class="button-grey confirm-delete" value="Yes" /><input type="button" class="button-grey decline-delete" value="No" /></div></div></div>');
            $(".address-delete-confirm").css("opacity", 0).stop().animate({ "opacity": 1 });
            $(".address-delete-confirm .confirm-delete").unbind().click(function () {
                var height = $(".checkout-loading").outerHeight(true);
                $(".checkout-address-form-loading").css("opacity", 0).stop().animate({ "height": height, "opacity": 1 });
                $(".address-delete-confirm").stop().animate({ "opacity": 0 }, function () { $(".address-delete-confirm").remove(); });
                _this.addressOperationAction(_this, section, scenario, url, data, loadingelement);
            });
            $(".address-delete-confirm .decline-delete").unbind().click(function () {
                $(".address-delete-confirm").stop().animate({ "opacity": 0 }, function () { $(".address-delete-confirm").remove(); });
            });
        }

        e.preventDefault();
        e.stopPropagation();
        return false;
    },

    addressOperationAction: function (_this, section, scenario, url, data, loadingelement) {
        // Makes ajax call, if required
        if (url != null && url != "") {
            $(".checkout-address-loading").css("opacity", 0).show().stop().animate({ "opacity": 1 });
            $(".checkout-address-display").stop().animate({ "opacity": 0, "height": $(".checkout-address-loading").height() });
            $.ajax({
                url: url,
                type: "POST",
                data: data
            }).done(function (response) {
                if (typeof (response.section) != "undefined") {
                    _this.renderResponseSection(section, response);
                } else {
                    $(".checkout-address-display").stop().animate({ "height": 0 });
                    if (scenario == 3 || scenario == 7) {
                        // Select/Clear selected address
                        if (response.addressType != null && response.displayAddress != null) {
                            $(".checkout-address-display").html(response.displayAddress);
                            $(".checkout-available-addresses .address-render-wrapper").removeClass("selected");
                            if (response.addressId != null && parseInt(response.addressId) > 0) {
                                $(".checkout-available-addresses .address-" + parseInt(response.addressId) + " .address-render-wrapper").addClass("selected");
                            }
                        }
                        $(".checkout-loading").stop().animate({ "opacity": 0 }, function () {
                            $(this).hide();
                        });
                        $(".checkout-address-display").stop().animate({ "height": $(".checkout-address-display .address-render").innerHeight() + $(".checkout-address-control").innerHeight(), "opacity": 1 }, function () {
                            if (scenario == 7) {
                                $("#opcaddresscontinue").show();
                            }
                        });
                    }
                    if (scenario == 2 || scenario == 4 || (scenario == 6 && response.success != null && response.success == false)) {
                        // Request new/edit address form
                        if (response.addressType != null && response.displayAddressForm != null) {
                            $(".render-address-form").html(response.displayAddressForm);
                            if (response.addressId != null && parseInt(response.addressId) > 0) {
                                $(".render-address-form").append('<input type="hidden" name="addressId" value="' + response.addressId + '" class="temp-form-input" />');
                            }
                            var height = $(".checkout-address-form").find(".checkout-address-section-wrapper").outerHeight(true);
                            $(".checkout-address-section.checkout-address-form").stop().animate({ "height": height });
                        }
                    }
                    if (scenario == 5 || scenario == 6) {
                        if (response.success != null && response.success == "True") {
                            if (response.addressType == "Shipping") {
                                if (response.availableShippingAddresses != null) {
                                    $(".checkout-available-addresses").html(response.availableShippingAddresses);
                                }
                                if (response.displayShippingAddress != null) {
                                    $(".checkout-address-display").html(response.displayShippingAddress);
                                }
                            } else if (response.addressType == "Billing") {
                                if (response.availableBillingAddresses != null) {
                                    $(".checkout-available-addresses").html(response.availableBillingAddresses);
                                }
                                if (response.displayBillingAddress != null) {
                                    $(".checkout-address-display").html(response.displayBillingAddress);
                                }
                            }

                            if (scenario == 5 || (scenario == 6 && response.addressId != null && parseInt(response.addressId) > 0)) {
                                // Back to available addresses
                                $(".checkout-address-section").stop().animate({ "height": 0 });
                                if (response.addressType != null) {
                                    var height = $(".checkout-available-addresses").find(".checkout-address-section-wrapper").outerHeight(true);
                                    $(".checkout-address-section.checkout-available-addresses").stop().animate({ "height": height });
                                }
                            } else {
                                // Select the address as form saved
                                $(".checkout-address-section").stop().animate({ "height": 0 });
                                $(".checkout-loading").stop().animate({ "opacity": 0 }, function () {
                                    $(this).hide();
                                });
                                $(".checkout-address-display").stop().animate({ "height": $(".checkout-address-display .address-render").innerHeight() + $(".checkout-address-control").innerHeight(), "opacity": 1 }, function () {
                                    $("#opcaddresscontinue").show();
                                });
                            }
                        } else {
                            $(".render-address-form").html(response.displayAddressForm).append('<input type="hidden" name="addressId" />');
                            $(".checkout-address-form").stop().animate({ "height": $(".render-address-form").height() });
                        }
                    }
                }
            }).always(function () {
                $(".checkout-address-loading").stop().animate({ "opacity": 0 }, function () {
                    $(this).hide();
                });
            }).error(function () {
                this.ajaxFailure();
            });
        } else {
            if (scenario == 1) {
                var height = $(".checkout-available-addresses").find(".checkout-address-section-wrapper").outerHeight(true);
                $(".checkout-address-section.checkout-available-addresses").stop().animate({ "height": height });
                loadingelement.stop().animate({ "opacity": 0 }, function () {
                    $(this).hide();
                });
            } else if (scenario == 8) {
                $(".checkout-address-display").stop().animate({ "height": $(".checkout-address-display .address-render").innerHeight() + $(".checkout-address-control").innerHeight(), "opacity": 1 }, function () {
                    if ($(".checkout-address-display .address-render").length) {
                        $("#opcaddresscontinue").show();
                    }
                });
                $(".checkout-loading").stop().animate({ "opacity": 0 }, function () {
                    $(this).hide();
                });
            }
        }
    },

    next: function (elem, e) {
        var section = elem.closest(".section"),
            form = elem.closest("form"),
            _this = this;
        section.find(".window-content").stop().animate({"opacity": 0});
        this.loadingBlock.stop().fadeIn(200);
        this.checkoutWrapper.stop().animate({ "height": this.loadingBlock.height() });
        if (typeof (elem.attr("data-card")) != "undefined") {
            $("#CreditCardId").remove();
            form.append('<input type="hidden" id="CreditCardId" name="CreditCardId" value="' + elem.attr("data-card") + '" />');
        }
        $.ajax({
            url: form.attr("action"),
            type: "POST",
            dataType: "JSON",
            data: form.serialize()
        }).error(function () {
            _this.ajaxFailure();
        }).done(function (response) {
            _this.renderResponseSection(section, response);
        });
        e.preventDefault();
        e.stopPropagation();
        return false;
    },

    edit: function (elem, e) {
        var editSection = elem.attr("data-section");
        var section = elem.closest(".section"),
            _this = this;
        section.find(".window-content").stop().animate({ "opacity": 0 });
        this.loadingBlock.stop().fadeIn(200);
        this.checkoutWrapper.stop().animate({ "height": this.loadingBlock.height() });
        $.ajax({
            url: this.editSectionUrl,
            type: "POST",
            dataType: "JSON",
            data: { sectionName: editSection }
        }).error(function () {
        }).done(function (response) {
            _this.renderResponseSection(section, response);
        });
        e.preventDefault();
        e.stopPropagation();
        return false;
    },

    renderResponseSection: function (section, response) {
        if (response == null || section == null || typeof section == "undefined") {
            this.ajaxFailure();
            return;
        }
        var _this = this;
        if (typeof (response.redirect) != "undefined") {
            location.href = response.redirect;
        } else {
            _this.loadingBlock.fadeOut(200);
            if (section.attr("id") == "opc-" + response.section) {
                _this.activateSection(section, response.updateHtml, true);
            } else {
                section.stop().animate({ "opacity": 0 }, 200, function () {
                    section.empty();
                    switch (response.section) {
                        case "shipping-address":
                            _this.activateSection(_this.shippingAddressSection, response.updateHtml, false);
                            break;
                        case "billing-address":
                            _this.activateSection(_this.billingAddressSection, response.updateHtml, false);
                            break;
                        case "shipping-methods":
                            _this.activateSection(_this.shippingMethodSection, response.updateHtml, false);
                            break;
                        case "payment-methods":
                            _this.activateSection(_this.paymentMethodSection, response.updateHtml, false);
                            break;
                        case "payment-info":
                            _this.activateSection(_this.paymentInfoSection, response.updateHtml, false);
                            break;
                        case "confirm":
                            _this.activateSection(_this.confirmSection, response.updateHtml, false);
                            break;
                    }
                });
            }
        }
    }
};
